package com.example.myiflytest;

//import android.os.Bundle;
//
//import com.google.android.material.snackbar.Snackbar;
//
//import androidx.appcompat.app.AppCompatActivity;
//
//import android.view.View;
//
//import androidx.navigation.NavController;
//import androidx.navigation.Navigation;
//import androidx.navigation.ui.AppBarConfiguration;
//import androidx.navigation.ui.NavigationUI;
//
//import com.example.myiflytest.databinding.ActivityMainBinding;
//
//import android.view.Menu;
//import android.view.MenuItem;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.myiflytest.databinding.ActivityMainBinding;
import com.google.android.material.snackbar.Snackbar;
import com.iflytek.xse.SEManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Environment;
import android.Manifest;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * 主活动类，用于测试回声消除SDK的功能
 */
public class MainActivity extends AppCompatActivity {
    // 权限请求码
    private static final int PERMISSION_REQUEST_CODE = 1;
    
    // 导航相关配置
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    
    // 回声消除管理器实例
    private SEManager seManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 检查并请求存储权限
        checkAndRequestPermissions();
        
        // 初始化视图绑定
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置工具栏
        setSupportActionBar(binding.toolbar);

        // 配置导航控制器
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        // 设置悬浮按钮点击事件，用于测试回声消除功能
        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testEchoCancellation();
                Snackbar.make(view, "开始测试回声消除", Snackbar.LENGTH_LONG)
                        .setAnchorView(R.id.fab)
                        .show();
            }
        });
    }

    /**
     * 检查并请求存储权限
     */
    private void checkAndRequestPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * 测试回声消除功能的主要方法
     */
    private void testEchoCancellation() {
        seManager = new SEManager();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 复制模型文件到手机存储
                    copyAssetsDir2Phone(MainActivity.this, "cae");

                    // 设置回调函数
                    seManager.setCallBack(new SEManager.WakeUp() {
                        @Override
                        public void onWakeUp(String data) {
                            Log.e("ivw", "———————————————" + data);
                        }

                        @Override
                        public void onStart(byte[] data) {
                            Log.d("SE", "onStart");
                        }

                        @Override
                        public void onRec(byte[] data) {
                            Log.d("SE", "onRec: " + data.length);
                        }

                        @Override
                        public void onEnd() {
                            Log.d("SE", "onEnd");
                        }

                        @Override
                        public void onSeData(byte[] data) {
                            // 处理回声消除后的数据
                            Log.d("SE", "onSeData: 收到处理后的数据，长度=" + data.length);
                            synchronized (MainActivity.this) {
                                try {
                                    // 保存处理后的数据到文件
                                    File outputDir = getExternalFilesDir("EchoCancellation");
                                    if (!outputDir.exists()) {
                                        outputDir.mkdirs();
                                    }

                                    File outputFile = new File(outputDir, "dealt.pcm");
                                    FileOutputStream fos = new FileOutputStream(outputFile, true);
                                    fos.write(data);
                                    fos.flush();
                                    fos.close();

                                    Log.d("SE", "已保存处理后的数据到: " + outputFile.getAbsolutePath() +
                                            ", 当前文件大小: " + outputFile.length());
                                } catch (IOException e) {
                                    Log.e("SE", "保存处理后的数据失败: " + e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        }
                    });

                    // 检查模型文件
                    String modelPath = getFilesDir().getAbsolutePath() + "/cae/models2mic";
                    File modelDir = new File(modelPath);
                    if (!modelDir.exists()) {
                        throw new IOException("模型目录不存在: " + modelPath);
                    }

                    // 检查必需的模型文件
                    String[] requiredModels = {
                            "mlp_aes_1024_tv.bin",
                            "mlp_td_fsmn_hxxj.bin",
                            "mlp_partition_2mic_3beam_512.bin"
                    };

                    for (String model : requiredModels) {
                        File modelFile = new File(modelPath, model);
                        if (!modelFile.exists()) {
                            throw new IOException("模型文件不存在: " + model);
                        }
                        Log.d("SE", "模型文件存在: " + modelFile.getAbsolutePath());
                    }

                    // 初始化SDK
                    seManager.create("8b415468", getFilesDir().getAbsolutePath());
                    Log.d("SE", "SDK初始化完成");

                    // 准备输出文件
                    File outputDir = new File(getExternalFilesDir(null), "EchoCancellation");
                    if (!outputDir.exists()) {
                        outputDir.mkdirs();
                    }
                    File outputFile = new File(outputDir, "out.pcm");
                    FileOutputStream outputStream = new FileOutputStream(outputFile);

                    // 处理音频数据
                    InputStream fileInputStream = getAssets().open("pcm/out_4ch.pcm");
                    byte[] data = new byte[640*4];
                    int read;
                    while ((read = fileInputStream.read(data)) != -1) {
                        if (read > 0) {
                            // 保存原始数据
                            outputStream.write(data, 0, read);
                            // 进行回声消除处理
                            seManager.writeData(data);
                        }
                    }

                    // 关闭文件流
                    fileInputStream.close();
                    outputStream.close();
                    Log.d("SE", "音频处理完成，输出文件保存在: " + outputFile.getAbsolutePath());

                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "测试出错: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 将assets目录下的文件复制到手机存储
     * @param activity 上下文
     * @param filePath 文件路径
     */
    protected static void copyAssetsDir2Phone(Context activity, String filePath) {
        try {
            String[] fileList = activity.getAssets().list(filePath);
            if (fileList.length > 0) {
                // 如果是目录，创建目录并递归复制
                File file = new File(activity.getFilesDir().getAbsolutePath() + File.separator + filePath);
                file.mkdirs();
                for (String fileName : fileList) {
                    filePath = filePath + File.separator + fileName;
                    copyAssetsDir2Phone(activity, filePath);
                    filePath = filePath.substring(0, filePath.lastIndexOf(File.separator));
                }
            } else {
                // 如果是文件，直接复制
                InputStream inputStream = activity.getAssets().open(filePath);
                File file = new File(activity.getFilesDir().getAbsolutePath() + File.separator + filePath);
                FileOutputStream fos = new FileOutputStream(file);
                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();
                inputStream.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限获取成功
                Toast.makeText(this, "存储权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                // 权限获取失败
                Toast.makeText(this, "需要存储权限才能保存音频文件", Toast.LENGTH_LONG).show();
            }
        }
    }
}